from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils import timezone

class MembershipType(models.Model):
    """会员类型模型"""
    name = models.CharField(max_length=50, verbose_name="会员类型名称")
    prompt_limit = models.IntegerField(default=1000, verbose_name="提示词数量限制")
    price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, verbose_name="价格")
    description = models.TextField(blank=True, null=True, verbose_name="描述")
    is_active = models.BooleanField(default=True, verbose_name="是否激活")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "会员类型"
        verbose_name_plural = "会员类型"

    def __str__(self):
        return self.name


class User(AbstractUser):
    """用户模型，扩展Django自带的用户模型"""
    phone = models.CharField(max_length=20, blank=True, null=True, verbose_name="手机号")
    membership = models.ForeignKey(
        MembershipType, 
        on_delete=models.SET_NULL, 
        null=True, 
        blank=True, 
        related_name="users",
        verbose_name="会员类型"
    )
    membership_expiry = models.DateTimeField(null=True, blank=True, verbose_name="会员到期时间")
    prompt_count = models.IntegerField(default=0, verbose_name="已创建提示词数量")
    is_admin = models.BooleanField(default=False, verbose_name="是否管理员")
    avatar = models.CharField(max_length=255, blank=True, null=True, verbose_name="头像URL")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "用户"
        verbose_name_plural = "用户"

    def __str__(self):
        return self.username

    @property
    def is_membership_active(self):
        """检查会员是否有效"""
        if not self.membership:
            return False
        if not self.membership_expiry:
            return False
        return self.membership_expiry > timezone.now()

    @property
    def can_add_prompt(self):
        """检查是否可以添加提示词"""
        if not self.membership:
            return False
        return self.prompt_count < self.membership.prompt_limit


class LoginLog(models.Model):
    """登录日志"""
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="login_logs", verbose_name="用户")
    ip_address = models.GenericIPAddressField(verbose_name="IP地址")
    user_agent = models.TextField(blank=True, null=True, verbose_name="用户代理")
    login_time = models.DateTimeField(auto_now_add=True, verbose_name="登录时间")
    is_success = models.BooleanField(default=True, verbose_name="是否成功")

    class Meta:
        verbose_name = "登录日志"
        verbose_name_plural = "登录日志"
        ordering = ['-login_time']

    def __str__(self):
        return f"{self.user.username} - {self.login_time}"
